package com.htl.线程.ConcurrentModificationException;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 *      计数信号量，实现限流操作，限制可以访问某些资源的线程数量。
 */

public class SemaphoreTest {
    public static void main(String[] args) {
        // 1、初始化
        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 15; i++) {
            new Thread(()->{
                try {
                    // 2、获得许可
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "进店购物");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "出店");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 3、释放
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
